<template>
  <i class="icon iconfont icon-saoyisao" @click="scan"></i>
</template>

<script>
import Vue from 'vue'

export default {
  name: 'QrScan',
  methods:{
    checkScan:function(){

    },
    scan : function () {
      let $this = this
      var winSize = Vue.prototype.getWinSize()
      var boxWidth = Math.floor(winSize.width * 0.8)
      var QRScan = api.require('QRScan')
      QRScan.customizedScanner({
        rect: {
          x: 0,   //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
          y: this.getSafeArea().top,   //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
          w: winSize.width, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
          h: winSize.height-(this.getSafeArea().top)  //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        },
        rectOfInterest: {
          x: Math.floor(winSize.width * 0.1),   //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
          y: Math.floor(winSize.height * 0.2),   //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
          w: boxWidth, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
          h: boxWidth  //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        },
        //tipString:'放入框内扫码',
        maskColor: 'rgba(0,0,0,0.5)',
        scanLine: {
          color: '#00FF00',
          thickness: 2
        },
        marginB: 30,
        // sound: 'fs://res/222.mp3',
        formatType: 'ALL'
      }, function (ret) {
        if (ret) {
          if (ret.status === true && ret.eventType === 'scan') {

              $this.MyQrAct(ret.result)
          }
          // callback(ret)
          // api.alert({msg: JSON.stringify(ret)})
          QRScan.closeCustomizedScanner()
        }
      })
    },
    MyQrAct : function (data) {
      let $this = this
      var qrData={}
      if (data.indexOf(dict.H5_UrlMap['H5_MEMBER_REGISTER']) > -1){
        qrData.event='Register'
      }else{
        qrData = JSON.parse(data)
      }

      switch (qrData.event) {
        // 1.邀请注册
        case 'Register':
          var url = data
          var urlArr = url.split('?')
          var queryString = urlArr[1]
          var queryArr = queryString.split('&')
          var queryMap = {}
          // api.alert({msg: 'queryArr: '+JSON.stringify(queryArr)})
          queryArr.forEach(function (str, index) {
            var strArr = str.split('=')
            queryMap[strArr[0]] = strArr[1]
          })
          if ($this.CurrUser.IsLogin()) {
            $this.CurrUser.setCache(null)
            $this.$confirm('当前操作需要退出登录?', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              $this.$router.push({
                name: 'Register',
                query: {
                  invitationCode: queryMap['invitationCode']
                }
              })
            }).catch(() => {
              //
            })
          } else {
            $this.$router.push({
              name: 'Register',
              query: {
                invitationCode: queryMap['invitationCode']
              }
            })
          }
          // api.alert({msg: '邀请码: ' + queryMap['invitationCode']})
          break
        // 2.团购参与
        case 'JoinGroupOrder':
          if (!qrData.orderNo || !qrData.invitationCode) {
            return $this.successTip('二维码不支持', 'warning')
          }
          $this.checkLoginAct(function () {
            $this.bus.$emit('GroupOrderJoinDialogCallBus', {
              invitationCode: qrData.invitationCode,
              // price: data.productPrice,
            })
          })
          break
        // 3.采购订单扫描,提交
        case 'ShopProductPurchase':
          // 获取采购订单信息
          // console.log('qrData',qrData)
          $this.checkLoginAct(function () {
            $this.MyRequest($this.ApiDoNameShop + 'Member/getShopProductPurchaseList', {orderNo: qrData.orderNo}, function (data) {
              // console.log('data',data)
              $this.$confirm('系统已经匹配到【采购订单】您是否前往提交?', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success'
              }).then(() => {
                var shopProductPurchaseOrder = {}
                if (data.list && data.list.length > 0) {
                  shopProductPurchaseOrder = data.list[0]
                } else {
                  return $this.successTip('采购订单不存在!', 'error')
                }
                // [{"image":"http://image.yangfankj.com/product/103/0.jpg","price":215.00,"name":"德国欧莱德-磨角机","model":"常规","id":8,"nums":1},{"image":"http://image.yangfankj.com/product/105/0.jpg","price":195.00,"name":"东成-气动直钉枪","model":"常规","id":11,"nums":5}]
                var tmpProductList = shopProductPurchaseOrder.productData
                var confirmOrderData = {
                  shop: {
                    id: shopProductPurchaseOrder.shopId,
                    name: shopProductPurchaseOrder.shopName,
                    logo: shopProductPurchaseOrder.shopLogo,
                  },
                  productList: []
                }
                tmpProductList.forEach(function (product, index) {
                  confirmOrderData.productList.push({
                    id: product.id,
                    name: product.name,
                    price: product.price,
                    image: product.image,
                    model: product.model,
                    nums: product.nums
                  })
                })

                // 存储: 店铺数据,商品数据
                localStorage.setItem('selectProductData', JSON.stringify(confirmOrderData))
                // 跳转至-订单确认页面
                $this.$router.push({
                  name: 'ConfirmOrder',
                  query: {
                    type: 'shopProductPurchase',
                    orderNo: shopProductPurchaseOrder.orderNo
                  }
                })
              }).catch(() => {
              })

            }, function () {

            })
          })
          break
        // 4.绑定店铺
        case 'BindingShop':
          $this.checkLoginAct(function () {
            $this.MyRequest($this.ApiDoNameShop + 'Member/bindingShop', {qrCode: qrData.qrCode}, function (data) {
              $this.successTip('绑定店铺成功!')
              // $this.bus.$emit('UserLoginCallBus')
            })
          })
          break
      }
    }
  }
}
</script>

<style scoped>

</style>
